<?php
/**
 * Created by PhpStorm.
 * User: yuyj
 * Date: 16-12-16
 * Time: 下午5:04
 */

namespace mybackend\controllers;

use common\entities\myhtsq\ActionCode;
use common\entities\outstock\MyscrmOutStockAttachmentEntity;
use common\entities\outstock\MyscrmOutStockOrderEntity;
use common\entities\outstock\MyscrmOutStockProductEntity;
use common\services\outstock\OutStockOrderService;
use Yii;

class OutStockOrderController extends BaseController
{

    private $service;

    public function __construct($id, $module, OutStockOrderService $outStockOrderService, $config = [])
    {
        $this->service = $outStockOrderService;
        parent::__construct($id, $module, $config);
    }

    protected function roleAuthRules()
    {
        $data = [
            'save' => ActionCode::FLOW_CENTER_OUT_STOCK,
            'view' => ActionCode::FLOW_CENTER_QUERY,
        ];

        return [
            'actions' => array_keys($data),
            'rules'   => [
                [
                    'allow'          => true,
                    'actionCodeMaps' => $data],
            ],
        ];
    }


    /*
     *
     * Author yuyj
     * Date 2017-01-04
     * @apiVersion 1.0.0
     * @api {post} /api/index.php/out-stock-order/save 创建出库申请单据
     * @apiGroup out-stock-order-controller
     *
     * @apiParam formData {string} order 单据信息
     * @apiParam formData {string} products 产品信息
     * @apiParam formData {string} attachments 附件信息
     *
     * @apiResponse 200 {
     *  "retCode": 0,
     *  "errMsg": "",
     *  "data": {"id": "a1", "name": "pen", "price": 101.2 }
     * }
     */
    public function actionSave()
    {
        /*$data = [
            'order'      => [
                //'id'                       => '39dc761a-ea64-89b6-5367-992e3509157b',//单据ID
                'business_pattern'         => 1,//1直属，2联营
                'contract_status'          => 1,//合同状态：1有，0没有
                'money_status'             => 0,//款项状态：1有，0没有
                'is_new_org'               => '',//是否新租户：1是，0否
                'org_id'                   => '',//租户CODE，不存在表示新租户
                'org_code'                 => '',//租户CODE，不存在表示新租户
                'contract_id'              => '39dc274f-e957-b9b0-376e-0490ac6a47b3',//关联合同ID
                'contract_code'            => 'SZSMYYKDZSWYXGS-GZWK-FW201612190131',//关联合同号
                'customer_id'              => '6c739f59-6ab3-4bc4-88da-1894d7f47e99',//客户ID
                'customer_name'            => '广州万科',//客户名称
                'customer_full_name'       => '广州万科股份有限公司',//客户全称
                'top_customer_name'        => '万科集团',//顶级客户名称
                'sign_people_id'           => '4cea7b02-eaaa-e211-bf86-848f69dfab16',//合同签约人ID 高红的userguid
                'sign_amount'              => '100000',//签约金额
                'promise_fulfil_time'      => date('Y-m-d'),//兑现日期
                'promise_fulfil_principle' => '4cea7b02-eaaa-e211-bf86-848f69dfab16',//兑现责任人ID
                //'request_user_id'          => '1',//请求人员ID
                'deliver_user_id'          => '4cea7b02-eaaa-e211-bf86-848f69dfab16',//交付人员ID
                //'response_user_id'         => '1',//响应人员ID
                //'order_status'             => 1,//单据状态 1正常 0 删除
                //'flow_status'              => 1,//流程状态 0未发起，10申请中，20已审批，21已确认，30已开通，31已授权
                //'flow_step_id'             => 1,//当前流程步骤ID
                'remarks'          => '',//备注
            ],
            'products'    => [
                [
                    'application_id'   => '080ac555-418d-11e5-812d-00155d02c832',// application_info ID
                    'application_name' => '明源云客电子商务平台-掌上售楼处',
                    'rent_period'      => '12',//租用周期（月）
                    'total_num'        => null,//总数量
                    'apply_num'        => 2,//申请数量
                    'contract_type'    => 1,//合同类型：1新增 2增购 3续签
                    'bind_project'     => [
                        ['proj_id' => '39cb319d-49c9-7262-ed8a-c7f155c7e46f', 'proj_name' => '石湖天玺'],
                        ['proj_id' => '39cb319d-49c9-7262-ed8a-c7f155c7e461', 'proj_name' => '石湖天玺'],
                    ],//绑定的项目ID
                    'remarks'          => '',//备注
                ],
            ],
            'attachments' => [
                [
                    'path'     => '/path/abc.pdf', //文件路径
                    'filename' => 'abc', //文件名
                ],
            ],
        ];

        Yii::$app->request->setBodyParams($data);*/

        $orderData = Yii::$app->request->post('order');
        $projectData = Yii::$app->request->post('products', []);
        $attachmentData = Yii::$app->request->post('attachments', []);

        /** @var MyscrmOutStockOrderEntity $order */
        $order = new MyscrmOutStockOrderEntity();
        $order->setAttributes($orderData);

        if (!$order->request_user_id) {
            $order->request_user_id = $this->getUserIdentity()->userguid;
        }

        $products = [];
        foreach ($projectData as $product) {
            // 申请数量为0,不作记录
            if ($product['apply_num'] <= 0) {
                continue;
            }

            if ($order->id) {
                $product['order_id'] = $order->id;
            }

            /** @var MyscrmOutStockProductEntity $model */
            $model = (new MyscrmOutStockProductEntity());
            $model->setAttributes($product);
            if (!$model->created_by) {
                $model->created_by = $this->getUserIdentity()->userguid;
            }

            $products[] = $model;
        }

        $attachments = [];
        foreach ($attachmentData as $attachment) {
            if ($order->id) {
                $attachment['order_id'] = $order->id;
            }

            /** @var MyscrmOutStockAttachmentEntity $model */
            $model = (new MyscrmOutStockAttachmentEntity());
            $model->setAttributes($attachment);

            if (!$model->created_by) {
                $model->created_by = $this->getUserIdentity()->userguid;
            }

            $attachments[] = $model;
        }

        $data = $this->service->save($order, $products, $attachments);

        return $this->exportJson($data, $this->service->getErrCode(), $this->service->getErrMsg());
    }

    /**
     *
     * @apiVersion  1.0.0
     * @api         {get} /api/index.php/out-stock-order/view 获取单据信息
     * @apiGroup    out-stock-order-controller
     * @apiParam    query {String} id 单据ID
     *
     * @apiResponse 200 {
     * "data": {
     * "order": {
     * "id{ID}": "39dc2731-94b6-6096-da74-4b697560773f",
     * "order_code{单据编号}": "20161219105909",
     * "business_pattern{1直属，2联营}": 1,
     * "contract_status{合同状态：1有，0没有}": 1,
     * "money_status{款项状态：1有，0没有}": 1,
     * "is_new_org{是否新租户：1是，0否}": "",
     * "org_id{租户id}": "",
     * "org_code{租户code}": "",
     * "contract_id{合同ID}": "39dc274f-e957-b9b0-376e-0490ac6a47b3",
     * "contract_code{合同编号}": "SZSMYYKDZSWYXGS-GZWK-FW201612190131",
     * "customer_id{客户ID}": "6c739f59-6ab3-4bc4-88da-1894d7f47e99",
     * "customer_name{客户简称}": "广州万科",
     * "customer_code{客户code}": "gzwk",
     * "customer_full_name{客户全称}": "广州万科股份有限公司",
     * "top_customer_name{顶级客户名称}": "万科集团",
     * "sign_people_id{签约人ID}": "4cea7b02-eaaa-e211-bf86-848f69dfab16",
     * "sign_amount{签约金额}": "100000.00",
     * "request_user_id{申请人ID}": "814eddb3-832e-e511-9b71-848f69dfab18",
     * "deliver_user_id{交付人员ID}": "4cea7b02-eaaa-e211-bf86-848f69dfab16",
     * "response_user_id{响应人员ID}": "",
     * "promise_fulfil_time{兑现日期}": "2016-12-21 00:00:00",
     * "promise_fulfil_principle{兑现责任人ID}": "4cea7b02-eaaa-e211-bf86-848f69dfab16",
     * "order_status{单据状态 1正常 0 删除}": 1,
     * "flow_status{流程状态 0未发起，10申请中，20已审批，21已确认，30已开通，31已授权}": 0,
     * "flow_step_id{当前流程ID}": "",
     * "remarks{备注}": "",
     * "created_on": "2016-12-19 10:59:17",
     * "modified_on": "2016-12-21 18:17:49"
     * },
     * "products": [
     * {
     * "id": "39dc330f-eba4-91c6-c88d-59bbf8f110f1",
     * "order_id": "39dc2731-94b6-6096-da74-4b697560773f",
     * "application_id": "080ac555-418d-11e5-812d-00155d02c832",
     * "application_name": "明源云客电子商务平台-掌上售楼处",
     * "rent_period{租用周期（月）}": 12,
     * "total_num{总数}": "",
     * "apply_num{申请数}": 10,
     * "contract_type{合同类型：1新增 2增购 3续签}": 1,
     * "bind_project{签约绑定的项目}": [
     *      {
     *      "proj_id{项目ID}": "39cb319d-49c9-7262-ed8a-c7f155c7e46f",
     *      "proj_name{项目名称}": "石湖天玺"
     *      }
     *  ],
     * "remarks{备注}": "",
     * "created_on": "2016-12-21 18:18:46",
     * "created_by": "814eddb3-832e-e511-9b71-848f69dfab18"
     * }
     * ],
     * "attachments": [
     * {
     * "id": "39dc330f-eba7-f311-ccbf-33fc1481c5ed",
     * "order_id": "39dc2731-94b6-6096-da74-4b697560773f",
     * "path": "/path/abc.pdf",
     * "filename": "abc",
     * "created_on": "2016-12-21 18:18:46",
     * "created_by": "814eddb3-832e-e511-9b71-848f69dfab18"
     * }
     * ]
     * },
     * "retCode": "0",
     * "errMsg": ""
     * }
     */
    public function actionView($id)
    {
        $data = $this->service->view($id);

        return $this->exportJson($data);
    }

    /**
     * 获取合同下的产品列表
     * @param $orgCode
     * @param $contractId
     * @param $orderId
     *
     * @apiVersion  1.0.0
     * @api         {get} /api/index.php/out-stock-order/get-product-list 获取合同下的产品列表
     * @apiGroup    out-stock-order-controller
     * @apiParam    query {String} contractId 合同ID
     * @apiParam    query {String} [orderId] 单据ID
     *
     * @apiResponse 200 {
     *
     * "data": [
     * {
     * "contract_application_id": "39dc60a4-afa3-e463-babf-0fe97790770a",
     * "application_id{申请应用ID}": "b0d6cb55-b4ed-11e5-b308-00155d02c832",
     * "authorization_type{授权类型  0：项目数  1：短信数}": "0",
     * "contract_type{合同属性，1新增，2增购，3续签}": "0",
     * "authorization_numeric{总授权数}": "10",
     * "application_name{应用名称}": "移动销售",
     * "allow_to_bind_project{是否允许绑定项目}": true,
     * "used_authorization_numeric{已使用授权数}": 0
     * }
     * ],
     * "retCode": "0",
     * "errMsg": ""
     * }
     */
    public function actionGetProductList($orgCode, $contractId, $orderId = null)
    {
        $data = $this->service->getContractApplicationByContractId($orgCode, $contractId, $orderId);

        return $this->exportJson($data, $this->service->getErrCode(), $this->service->getErrMsg());
    }

    /**
     * @apiVersion  1.0.0
     * @api         {get} /api/index.php/out-stock-order/get-application-list 获取所有产品列表
     * @apiGroup    out-stock-order-controller
     *
     * @apiResponse 200 {
     *
     * "data": [
     * {
     * "application_id{应用ID}": "080ac555-418d-11e5-812d-00155d02c832",
     * "application_name{应用名称}": "掌上售楼处",
     * "allow_to_bind_project{是否允许绑定项目}": true
     * }
     * ],
     * "retCode": "0",
     * "errMsg": ""
     * }
     */
    public function actionGetApplicationList()
    {
        $data = $this->service->getApplicationList();

        return $this->exportJson($data, $this->service->getErrCode(), $this->service->getErrMsg());
    }

    /*
    * Author yuyj
    * Date 2017-01-03
    * @apiVersion 1.0.0
    * @api {get} /api/index.php/out-stock-order/get-project-list 根据应用ID获取需要授权的项目列表
    * @apiGroup out-stock-order-controller
    *
    * @apiParam query {string} orgCode 租户code
    * @apiParam query {string} authorizeApplicationId 授权的应用ID
    *
    * @apiResponse 200 {
    * "data": [
    *       {
    *       "ProjId{项目ID}": "39dc524c-8563-3db6-8714-05cc316ca138",
    *       "ProjName{项目名称}": "yb123"
    *       }
    * ],
    * "retCode": "0",
    * "errMsg": ""
    * }
    */
    public function actionGetProjectList($orgCode, $authorizeApplicationId, $status)
    {
        $status = explode(',', $status);

        $isOverdue = 0;
        foreach ($status as $key => $item){
            if ($item == 0){
                $isOverdue = 1;
                unset($status[$key]);
                break;
            }
        }

        $data = $this->service->getProjectList($orgCode, $authorizeApplicationId, $status, $isOverdue);

        return $this->exportJson($data, $this->service->getErrCode(), $this->service->getErrMsg());
    }

    /*
     *
     * Author yuyj
     * Date 2017-01-14
     * @apiVersion 1.0.0
     * @api {post} /api/index.php/out-stock-order/delete 删除单据
     * @apiGroup out-stock-order-controller
     * @apiParam formData {string} id 单据ID
     *
     * @apiResponse 200 {
     *  "retCode": 0,
     *  "errMsg": "",
     *  "data": true
     * }
     */
    public function actionDelete()
    {
        $id = Yii::$app->request->post('id');

        $data = $this->service->delete($id);

        return $this->exportJson($data);
    }

}